<script setup>
import {ref, defineProps, defineEmits} from "vue";

const isEdit = ref(false);

defineProps({
  value: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:value'])

const handleEnter = (e) => {
  // 非空处理
  if (e.target.value.trim() === '') return alert('标签不能为空');

  // 子传父，将回车时，[输入框的内容] 提交给父组件更新
  // 由于父组件是v-model，触发事件，需要触发 update:value 事件
  emit('update:value', e.target.value);

  // 提交完成，关闭输入状态
  isEdit.value = false;
}
</script>

<template>
  <div class="my-tag">
    <input
        v-if="isEdit"
        v-focus
        @blur="isEdit = false"
        :value="value"
        @keyup.enter="handleEnter"
        class="input"
        type="text"
        placeholder="输入标签"
    />
    <div
        v-else
        @click="isEdit = true"
        class="text">
      {{ value }}
    </div>
  </div>
</template>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;

  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;

    &::placeholder {
      color: #666;
    }
  }
}
</style>